package com.anyext.storage.util.template;

import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public class StringTemplate {

	private static Configuration		cfg		= new Configuration();
	private static StringTemplateLoader	loader	= new StringTemplateLoader();

	static {
		cfg.setTemplateLoader(loader);
		cfg.setDefaultEncoding("UTF-8");
		cfg.setTagSyntax(Configuration.AUTO_DETECT_TAG_SYNTAX);
	}

	public static void putTemplate(String name, String templateSource) {
		loader.putTemplate(name, templateSource);
	}

	public static String process(String name, Map<String, Object> valueMap) {
		StringWriter writer = new StringWriter();
		try {
			Template template = cfg.getTemplate(name);
			template.process(valueMap, writer);
		} catch (IOException e) {
			e.printStackTrace();
		} catch (TemplateException e) {
			e.printStackTrace();
		}
		return writer.toString();
	}

	public static void main(String[] args) {
		Log log = LogFactory.getLog(StringTemplate.class);
		String sql = "${r'$'}{time}";// \\${time}
		sql = "\\@WS";// \\@WS
		sql = "${r'@'}WS";// \\@WS
		sql = "${msg}";// \\@WS
		StringTemplate.putTemplate("sql", sql);
		long s = System.currentTimeMillis();
		for (int i = 0; i < 100000; i++) {
			Map<String, Object> values = new HashMap<String, Object>();
			values.put("msg", "text" + i);
			System.out.println(StringTemplate.process("sql", values));
			log.info(StringTemplate.process("sql", values));
			StringTemplate.process("sql", values);
		}
		System.out.println(System.currentTimeMillis() - s);
	}

}
